/*
 * Copyright (c) 2017 Baidu, Inc. All Rights Reserve.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.baidu.fsg.uid;

import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;
import org.springframework.util.Assert;

/**
 * bit分配器
 *
 * Allocate 64 bits for the UID(long)<br>
 * sign (fixed 1bit) -> deltaSecond -> workerId -> sequence(within the same second)
 * 
 * @author yutianbao
 */
public class BitsAllocator {
    /**
     * 总的bit位数, 常量2^6=64
     * Total 64 bits
     */
    public static final int TOTAL_BITS = 1 << 6;

    /**
     * 符号位, 1bit, 永远为0
     * Bits for [sign-> second-> workId-> sequence]
     */
    private int signBits = 1;

    /**
     * 时间戳位数, 由用户指定, 单位为秒
     */
    private final int timestampBits;

    /**
     * 工作ID位数, 由用户指定
     */
    private final int workerIdBits;


    /**
     * 序号位数, 由用户指定
     */
    private final int sequenceBits;

    /**
     * Max value for workId & sequence
     */

    /**
     * 最大的秒数值 = 2^timestampBits - 1 = ~ (-1L << timestampBits)
     * 也是时间戳的掩码
     */
    private final long maxDeltaSeconds;

    /**
     * 最大的工作ID = 2^workerIdBits - 1 = ~ (-1L << workerIdBits)
     */
    private final long maxWorkerId;

    /**
     * 最大的序号值 = 2^sequenceBits - 1 = ~ (-1L << sequenceBits)
     */
    private final long maxSequence;

    /**
     * Shift for timestamp & workerId
     */

    /**
     * 时间戳左移位数 = workerIdBits + sequenceBits
     */
    private final int timestampShift;

    /**
     * 工作ID左移位数 = sequenceBits
     */
    private final int workerIdShift;

    /**
     * Constructor with timestampBits, workerIdBits, sequenceBits<br>
     * The highest bit used for sign, so <code>63</code> bits for timestampBits, workerIdBits, sequenceBits
     */
    public BitsAllocator(int timestampBits, int workerIdBits, int sequenceBits) {
        // 1. 校验分配的bit位数是否得等于64位
        // make sure allocated 64 bits
        int allocateTotalBits = signBits + timestampBits + workerIdBits + sequenceBits;
        Assert.isTrue(allocateTotalBits == TOTAL_BITS, "allocate not enough 64 bits");

        // 2. 初始化值
        // initialize bits
        this.timestampBits = timestampBits;
        this.workerIdBits = workerIdBits;
        this.sequenceBits = sequenceBits;

        // -1       11111111 11111111 11111111 11111111 11111111 11111111 11111111 11111111
        // 左移5位   11111111 11111111 11111111 11111111 11111111 11111111 11111111 11100000
        // 取反     00000000 00000000 00000000 00000000 00000000 00000000 00000000 00011111

        // initialize max value
        this.maxDeltaSeconds = ~(-1L << timestampBits);
        this.maxWorkerId = ~(-1L << workerIdBits);
        this.maxSequence = ~(-1L << sequenceBits);

        // initialize shift
        this.timestampShift = workerIdBits + sequenceBits;

        this.workerIdShift = sequenceBits;
    }

    /**
     * 计算唯一ID
     *
     * Allocate bits for UID according to delta seconds & workerId & sequence<br>
     * <b>Note that: </b>The highest bit will always be 0 for sign
     * 
     * @param deltaSeconds 时间差， 单位秒
     * @param workerId 工作ID
     * @param sequence 序号
     * @return
     */
    public long allocate(long deltaSeconds, long workerId, long sequence) {
        return (deltaSeconds << timestampShift) | (workerId << workerIdShift) | sequence;
    }
    
    /**
     * Getters
     */
    public int getSignBits() {
        return signBits;
    }

    public int getTimestampBits() {
        return timestampBits;
    }

    public int getWorkerIdBits() {
        return workerIdBits;
    }

    public int getSequenceBits() {
        return sequenceBits;
    }

    public long getMaxDeltaSeconds() {
        return maxDeltaSeconds;
    }

    public long getMaxWorkerId() {
        return maxWorkerId;
    }

    public long getMaxSequence() {
        return maxSequence;
    }

    public int getTimestampShift() {
        return timestampShift;
    }

    public int getWorkerIdShift() {
        return workerIdShift;
    }
    
    @Override
    public String toString() {
        return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE);
    }

    public static void main(String[] args) {
        BitsAllocator bitsAllocator = new BitsAllocator(28,22,13);
        System.out.println(bitsAllocator);
    }
    
}